package _interview150;

/**
 * 221. 最大正方形
 */
public class No221 {
    private char[][] matrix;
    private int[][] cache;
    private int maxSide;

    public int maximalSquare(char[][] matrix) {
        this.matrix = matrix;
        int m = matrix.length;
        int n = matrix[0].length;

        cache = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                cache[i][j] = -1;
            }
        }

        maxSide = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dfs(i, j);
            }
        }
        return maxSide * maxSide;
    }

    private int dfs(int i, int j) {
        if (i < 0 || j < 0) return 0;
        else if (cache[i][j] != -1) return cache[i][j];
        else if (matrix[i][j] == '0') return cache[i][j] = 0;
        int curSide = Math.min(dfs(i - 1, j - 1), Math.min(dfs(i, j - 1), dfs(i - 1, j))) + 1;
        maxSide = Math.max(curSide, maxSide);
        return cache[i][j] = curSide;
    }
}
